using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using Common;
using Common.Utilities;
using Common.Utilities.Dispatcher;
using Workflows.Components;

namespace Workflows.Components.Communication
{
    /// <summary>
    /// 
    /// </summary>
    public partial class EmailEditor : Form, IComponentEditor
    {
        private object _ActivityNode;
        private EmailComponent _EmailComponent;

        /// <summary>
        /// 
        /// </summary>
        public EmailEditor()
        {
            InitializeComponent();
        }

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        public object OwnerActivityNode
        {
            get { return _ActivityNode; }
            set { _ActivityNode = value; }
        }

        public Type WorkflowComponentType
        {
            get { return typeof(EmailComponent); }
        }



        public void LoadSettings(GlobalVariable[] globalVars,
            WorkflowComponentBase[] fromComponents, 
            object activityNode, WorkflowComponentBase wfComponent)
        {
            this._ActivityNode = activityNode;
            this._EmailComponent = (EmailComponent) wfComponent;

            this.txt_SmtpServer.Text = this._EmailComponent.SmtpServer;
            this.txt_From.Text = this._EmailComponent.FromAddress;
            this.txt_To.Text = this._EmailComponent.ToAddresses;
            this.txt_Subject.Text = this._EmailComponent.Subject;
            this.rt_BodyTemplate.Text = this._EmailComponent.BodyTemplate;
            this.ck_Authentication.Checked = this._EmailComponent.RequireAuthentication;
            this.txt_UserName.Text = this._EmailComponent.UserName;
            this.txt_Password.Text = this._EmailComponent.Password;
            this.dv_Attachment.Rows.Clear();
            if(this._EmailComponent.Attachments!=null && this._EmailComponent.Attachments.Length>0)
            {
                foreach(string filePath in this._EmailComponent.Attachments)
                {
                    DataGridViewRow dr=new DataGridViewRow();
                    DataGridViewTextBoxCell cellFilePath = new DataGridViewTextBoxCell();
                    cellFilePath.Value = filePath;
                    dr.Cells.Add(cellFilePath);

                    DataGridViewButtonCell cellBrowse=new DataGridViewButtonCell();
                    cellBrowse.Value = "Browse";
                    dr.Cells.Add(cellBrowse);
                    this.dv_Attachment.Rows.Add(dr);
                }
            }
            this.ck_UseOutlook.Checked = this._EmailComponent.UseOutlookClient;
            this.ck_EnableSSL.Checked = this._EmailComponent.EnableSSL;

            this.dv_PlaceHolders.Rows.Clear();
            if(this._EmailComponent.BodyPlaceHolders !=null && this._EmailComponent.BodyPlaceHolders.Count>0)
            {
                foreach(string name in this._EmailComponent.BodyPlaceHolders.Keys)
                {
                    DataGridViewRow dr = new DataGridViewRow();
                    DataGridViewTextBoxCell cellName=new DataGridViewTextBoxCell();
                    cellName.Value = name;
                    dr.Cells.Add(cellName);
                    DataGridViewTextBoxCell cellVal = new DataGridViewTextBoxCell();
                    cellVal.Value = this._EmailComponent.BodyPlaceHolders[name];
                    dr.Cells.Add(cellVal);
                    this.dv_PlaceHolders.Rows.Add(dr);
                }
            }
        }

        public void SaveSettings()
        {
            this._EmailComponent.BodyTemplate = this.rt_BodyTemplate.Text;
            this._EmailComponent.FromAddress = this.txt_From.Text;
            this._EmailComponent.SmtpServer = this.txt_SmtpServer.Text;
            this._EmailComponent.Subject = this.txt_Subject.Text;
            this._EmailComponent.ToAddresses = this.txt_To.Text;
            this._EmailComponent.RequireAuthentication = this.ck_Authentication.Checked;
            this._EmailComponent.UserName = this.txt_UserName.Text;
            this._EmailComponent.Password = this.txt_Password.Text;
            this._EmailComponent.Attachments = null;
            this._EmailComponent.UseOutlookClient = this.ck_UseOutlook.Checked;
            this._EmailComponent.EnableSSL = this.ck_EnableSSL.Checked;

            if (this.dv_Attachment.Rows.Count > 0)
            {
                List<string> filePaths = new List<string>();
                foreach (DataGridViewRow dr in this.dv_Attachment.Rows)
                {
                    if (!dr.IsNewRow)
                    {
                        DataGridViewTextBoxCell cellFilePath = (DataGridViewTextBoxCell) dr.Cells[0];
                        if (cellFilePath.Value != null)
                        {
                            string filePath = cellFilePath.Value.ToString();
                            if (!string.IsNullOrEmpty(filePath))
                            {
                                filePaths.Add(filePath);
                            }
                        }
                    }
                }
                this._EmailComponent.Attachments = filePaths.ToArray();
            }

            this._EmailComponent.BodyPlaceHolders=new Dictionary<string, string>();
            foreach(DataGridViewRow dr in this.dv_PlaceHolders.Rows)
            {
                if(!dr.IsNewRow && dr.Cells[0].Value !=null)
                {
                    string name = dr.Cells[0].Value.ToString();
                    string val = null;
                    if(dr.Cells[1].Value !=null)
                        val = dr.Cells[1].Value.ToString();
                    this._EmailComponent.BodyPlaceHolders.Add(name,val);
                }
            }
        }

        private void ck_Authentication_CheckedChanged(object sender, EventArgs e)
        {
            if(this.ck_Authentication.Checked)
            {
                this.txt_UserName.Enabled = true;
                this.txt_Password.Enabled = true;
            }
            else
            {
                this.txt_UserName.Enabled = false;
                this.txt_Password.Enabled = false;
            }
        }

        private void EmailEditor_Load(object sender, EventArgs e)
        {
            if(ConfigurationManager.AppSettings.Get("SmtpServer")!=null)
            {
                this.txt_SmtpServer.Text = ConfigurationManager.AppSettings.Get("SmtpServer");
            }
            this.ck_Authentication.Checked = true;
            this.txt_UserName.Text = "li.xiaodong@DiscoveryLogic.com";
            this.txt_Password.Text = "xiaodong";
            this.txt_From.Text = "Wokflow@DiscoveryLogic.com";
            this.txt_Subject.Text = "Subject";
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            if(this.UpdateComponentSettingEvent !=null)
            {
                this.SaveSettings();
                this.UpdateComponentSettingEvent(this._ActivityNode, this._EmailComponent);
            }
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Test_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            EmailInstruction instruction = new EmailInstruction(
                this._EmailComponent.ComponentID, Guid.Empty,
                this._EmailComponent.SmtpServer,
                this._EmailComponent.FromAddress,
                this._EmailComponent.ToAddresses,
                string.Empty,
                this._EmailComponent.Subject,
                MailPriority.Normal,
                this.ck_Authentication.Checked,
                this.txt_UserName.Text,
                this.txt_Password.Text,
                this._EmailComponent.Attachments,
                this.rt_BodyTemplate.Text,
                this._EmailComponent.UseOutlookClient,
                this._EmailComponent.EnableSSL,
                this._EmailComponent.BodyPlaceHolders);
            EmailWorker worker=new EmailWorker();
            worker.SetInstruction(Guid.NewGuid(),instruction, string.Empty, this._EmailComponent.ComponentName);
            worker.WorkerFinishedEvent += new WorkerFinished(worker_WorkerFinishedEvent);
            worker.WorkerStatusChangedEvent += new WorkerStatusChanged(worker_WorkerStatusChangedEvent);
            worker.WorkerStartedEvent += new WorkerStarted(worker_WorkerStartedEvent);
            worker.WorkerErredEvent += new WorkerHasError(worker_WorkerErredEvent);
            worker.DoWork();
        }

        public TestResult Test()
        {
            return new TestResult(true, string.Empty);
        }

        void worker_WorkerErredEvent(Guid ticketID, Type workerType, InstructionBase instructionBase, string error, bool isFatal)
        {
            this.DisplayStatus("Error: " + error,0);
        }

        void worker_WorkerStartedEvent(Guid ticketID, IWorker workerReference, Type workerType, InstructionBase instructionBase)
        {
            this.DisplayStatus("Starting email worker...",5);
        }

        void worker_WorkerStatusChangedEvent(Guid ticketID, Type workerType, InstructionBase instructionBase, 
            string workflowName, string componentName, string message, int percent)
        {
            this.DisplayStatus(message,percent);
        }

        void worker_WorkerFinishedEvent(Guid ticketID, Type workerType, InstructionBase instructionBase, ResultBase resultBase)
        {
            this.DisplayStatus("Email sent.",0);
        }

        private void DisplayStatus(string message, int percent)
        {
            if(percent>0)
            {
                this.desktopAlert1.ShowAlert(message + ", " + percent + "%");
            }
            else
            {
                this.desktopAlert1.ShowAlert(message);
            }
        }

        private void dv_Attachment_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex==1 && e.RowIndex>=0 && !this.dv_Attachment.Rows[e.RowIndex].IsNewRow)
            {
                DataGridViewRow dr = this.dv_Attachment.Rows[e.RowIndex];
                OpenFileDialog dlg=new OpenFileDialog();
                if(dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)
                {
                    string fileName = dlg.FileName;
                    ((DataGridViewTextBoxCell) dr.Cells[0]).Value = fileName;
                    ((DataGridViewButtonCell) dr.Cells[1]).Value = "Browse";
                }
            }
        }

        private void ck_UseOutlook_CheckedChanged(object sender, EventArgs e)
        {
            if(this.ck_UseOutlook.Checked)
            {
                this.txt_SmtpServer.Enabled = false;
                this.txt_From.Enabled = false;
            }
            else
            {
                this.txt_SmtpServer.Enabled = true;
                this.txt_From.Enabled = true;
            }
        }
    }
}